""" 

    Challenge.py used in RepresentedBy Facebook application
    http://apps.facebook.com/representedby/
    
    This page displays information about the challenge, including:
        - The leaderboard
        - History of past matches
        - Pending Matches
        - Links to invite your friends to take the challenge
        
"""

__author__ = "Will Turnage (will@wubbahed.com)"
__version__ = "0.1.0"
__copyright__ = "Copyright (c) 2009 wubbahed.com"
__license__ = "GPLv3"


import os
import wsgiref.handlers
import facebook
import const
import string

from cgi import escape
from sets import Set
from django.utils import simplejson
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.api import urlfetch
from google.appengine.ext import db
from utils import fbUtil, dbUtil, UserDistrict, SunlightUtil, Leaderboard, Challenges, EntryPoint

class MainHandler(webapp.RequestHandler):
    def post(self):
        
        try:
            
            #check if Facebook app is installed
            self.facebookapi = fbUtil().checkFacebookAppInstalled(self, True, "challenge")
            if self.facebookapi is None:
                return
            
            challenge_data = {}
            #todo - test with multiple users or LIMIT TO ONE?
            theId = self.request.get('ids[]', default_value=None)
            if theId is not None:
                
                if not self.facebookapi.users.isAppUser(int(theId)):
                    query = EntryPoint.get_or_insert("user"+str(theId), uid=int(theId), section=str("quiz"))
                    query.put()
                
                challenge = Challenges.get_or_insert("user"+str(theId), challengee=int(theId))
                if not challenge.completed:
                    if challenge.challenger is None:
                        challenge.challenger = int(self.facebookapi.uid)
                        challenge.put()
                        if challenge_data.has_key("challenge_count"):
                            challenge_data["challenge_count"] = challenge_data["challenge_count"] + 1
                        else:
                            challenge_data["challenge_count"] = 1
            
            myvars = {"section": "challenge"}
            path = os.path.join(os.path.dirname(__file__), '../templates/heading.fbml')
            self.response.out.write(template.render(path, myvars))
            
            friends_with_app_ids = self.facebookapi.friends.getAppUsers()
            if friends_with_app_ids is None:
                friends_with_app_ids = [int(self.facebookapi.uid)]
            elif len(friends_with_app_ids) == 0:
                friends_with_app_ids = [int(self.facebookapi.uid)]
            else:
                friends_with_app_ids.append(int(self.facebookapi.uid))
            
            friend_data = {}
            friend_raw_data = self.facebookapi.users.getInfo(friends_with_app_ids, ['uid', 'name'])
            for friend in friend_raw_data:
                friend_data[int(friend["uid"])] = {"id": int(friend["uid"]), "name": friend["name"], "totalscore": 0, "yourscore": 0, "theirscore": 0,"challenge_completed": False, "challenged_by_you": False}
    
            leaderboard = []
            recentmatches = []
            pendingchallenges = []
            completedchallenge = []
            
            for friend in friend_data.keys():
                query = Challenges.all()
                query.filter("challengee =", friend)
                results = query.fetch(1)
                for result in results:
                    if result.completed:
                        completedchallenge.append(friend)
                    if result.challenger == int(self.facebookapi.uid):
                        if result.completed:     
                            recentmatches.append({"challenger":"You", "challengee": friend_data[friend]["name"], "challenger_score": result.challengerscore, "challengee_score": result.challengeescore })
                        else:
                            pendingchallenges.append({"name": friend_data[friend]["name"], "id":friend} )
                    if (result.challengee == int(self.facebookapi.uid)) and (result.completed):    
                        tempDict = {"challengee":"You", "challenger_score": result.challengerscore, "challengee_score": result.challengeescore }
                        if friend_data.has_key(result.challenger):
                            tempDict["challenger"] = friend_data[result.challenger]["name"]
                        elif friend_data.has_key(str(result.challenger)):
                            tempDict["challenger"] = friend_data[str(result.challenger)]["name"]
                        recentmatches.append(tempDict)
        
                               
                query = Leaderboard.all()
                query.filter("uid =", friend)
                results = query.fetch(1)
                for result in results:
                    if result.score > 0:
                        friend_data[friend]["totalscore"] = result.score
                        leaderboard.append((result.score, friend_data[friend]["name"]))
       
            

                        
            query = Challenges.all()
            query.filter("challengee =", int(self.facebookapi.uid))
            query.filter("completed =", False)
            results = query.fetch(1)
            for result in results:
                challenge_data["outstanding_challenge"] = friend_data[result.challenger]["name"]  
         
            leaderboard.sort(reverse=False)
            

            challenge_data["leaderboard"] = leaderboard
            challenge_data["recentmatches"] = recentmatches
            challenge_data["pendingchallenges"] = pendingchallenges
            challenge_data["completedchallenge"] = completedchallenge
            challenge_data["challenge_button"] = escape("<fb:req-choice url=\"http://apps.facebook.com/representedby/quiz\" label=\"Accept the Challenge\" />", True)
            
            path = os.path.join(os.path.dirname(__file__), '../templates/challenge.fbml')
            self.response.out.write(template.render(path, challenge_data ))
            
            
        except urlfetch.DownloadError, e:
            path = os.path.join(os.path.dirname(__file__), '../templates/error.fbml')
            self.response.out.write(template.render(path, {"error":"Sorry, Google AppEngine ain't working" }))
            
        except facebook.FacebookError, e:
            path = os.path.join(os.path.dirname(__file__), '../templates/error.fbml')
            self.response.out.write(template.render(path, {"error":"Sorry, Facebook ain't working - " + str(e.msg)})) 
            
  
def main():
	application = webapp.WSGIApplication([('/fb/challenge', MainHandler)],
									   debug=True)
	run_wsgi_app(application)

# load our custom filters		   
webapp.template.register_template_library('customfilters')

if __name__ == '__main__':
	main()
